/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package stendcontrol;

import com.sun.org.apache.xerces.internal.impl.io.UTF8Reader;
import gui.ArrayListModel;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import services.ConvFileName;

/**
 *
 * @author minaev
 */
public class ResearchContainer {

    private ArrayListModel<Research> researches = new ArrayListModel<Research>();

    public Research getResearch(int n) {
        return researches.get(n);
    }

    public void addResearch(Research res) {
        researches.add(res);
    }

    public void removeReseach(Research res) {
        researches.remove(res);
    }

    public void removeResearch(int n) {
        researches.remove(n);
    }

    public void removeAllResearches() {
        researches.clear();
    }

    public ArrayListModel<Research> getResearches() {
        return researches;
    }

    private void warningFileExt(String file_ext) {
        if (!(file_ext.charAt(0) == '.')) {
            StendLogger.log(StendLogger.MSG_WARNING, "File ext: \"" + file_ext
                    + "\" must start with \".\" example: .rsch");
        }
    }

    /**
     * Загрузить список экспериментов из директории
     *
     * @param dir - директория, из которой производится загрузка
     * @param file_ext - расширение файлов, содержащих эксперименты
     */
    public void loadReseachesFromDirectory(String dir, final String file_ext) {
        warningFileExt(file_ext);
        File fdir = new File(dir);
        if (fdir.exists()) {
            if (fdir.isDirectory()) {
                File[] files = fdir.listFiles(new FileFilter() {
                    @Override
                    public boolean accept(File pathname) {
                        String path = pathname.getAbsolutePath();
                        return path.substring(path.length() - file_ext.length())
                                .equals(file_ext);
                    }
                });
                for (File fl : files) {
                    addFromFile(fl);
                }

            } else {
                StendLogger.log(StendLogger.MSG_ERROR, "It is not directory: "
                        + dir);
            }
        } else {
            StendLogger.log(StendLogger.MSG_ERROR, "Directory not exsist: "
                    + dir);
        }
    }

    public void loadReseachesFromDirectory() {
        String dir = (String) Configurator.getConf()
                .getProperty(Configurator.RESEARCH_PATH);
        String file_ext = (String) Configurator.getConf()
                .getProperty(Configurator.RESEARCH_EXT_FILES);
        loadReseachesFromDirectory(dir, file_ext);
    }

    public void saveResearchesToDirectory(String dir, String file_ext) {
        warningFileExt(file_ext);
        File fdir = new File(dir);
        if (fdir.exists()) {
            if (fdir.isDirectory()) {
                for (Research rsch : researches) {
                    saveToFile(rsch, new File(fdir.getAbsolutePath()
                            + File.separator
                            + ConvFileName.convertName(
                            rsch.getName() + file_ext)));
                }
            } else {
                StendLogger.log(StendLogger.MSG_ERROR, "It is not save "
                        + "directory: " + dir);
            }
        } else {
            StendLogger.log(StendLogger.MSG_ERROR, "Save directory not exsist: "
                    + dir);
        }
    }

    public void saveToFile(Research rsch) {
        String dir = (String) Configurator.getConf()
                .getProperty(Configurator.RESEARCH_PATH);
        String file_ext = (String) Configurator.getConf()
                .getProperty(Configurator.RESEARCH_EXT_FILES);

        warningFileExt(file_ext);
        File fdir = new File(dir);
        if (fdir.exists()) {
            if (fdir.isDirectory()) {
                saveToFile(rsch, new File(fdir.getAbsolutePath()
                        + File.separator
                        + ConvFileName.convertName(
                        rsch.getName() + file_ext)));
            } else {
                StendLogger.log(StendLogger.MSG_ERROR, "It is not save "
                        + "directory: " + dir);
            }
        } else {
            StendLogger.log(StendLogger.MSG_ERROR, "Save directory not exsist: "
                    + dir);
        }
    }

    public void saveToFile(Research rsch, File frsch) {
        FileOutputStream fos;
        try {
            fos = new FileOutputStream(frsch);

            try {
                fos.write(rsch.getCode().getBytes("UTF-8"));
            } catch (IOException ex) {
                StendLogger.log(StendLogger.MSG_ERROR, "Output error in save "
                        + "research. File:" + "\"" + frsch.getAbsolutePath()
                        + "\" : " + ex.getMessage());
            }
            try {
                fos.close();
            } catch (IOException ex) {
                StendLogger.log(StendLogger.MSG_ERROR, "Close error in save "
                        + "research. File:" + "\"" + frsch.getAbsolutePath()
                        + "\" : " + ex.getMessage());
            }
        } catch (FileNotFoundException ex) {
            StendLogger.log(StendLogger.MSG_ERROR, "Save Research error. File "
                    + "\"" + frsch.getAbsolutePath() + "\" not exists: "
                    + ex.getMessage());
        }
    }

    public void addFromFile(File frsch) {
        String code = "";
        int buf;
        FileInputStream fis;
        UTF8Reader utf_reader;
        try {
            fis = new FileInputStream(frsch);
            utf_reader = new UTF8Reader(fis);

            while ((buf = utf_reader.read()) != -1) {
                code += (char) buf;
            }

            fis.close();
        } catch (FileNotFoundException ex) {
            StendLogger.log(StendLogger.MSG_ERROR, "Load Research error. File "
                    + "\"" + frsch.getAbsolutePath() + "\" not exists: "
                    + ex.getMessage());
        } catch (IOException ex) {
            StendLogger.log(StendLogger.MSG_ERROR, "Input error in load "
                    + "research. File:" + "\"" + frsch.getAbsolutePath()
                    + "\" : " + ex.getMessage());
        }

        String path_name = frsch.getName();
        int last_pnt = path_name.length();
        for (int i = 0; i < path_name.length(); i++) {
            if (path_name.charAt(i) == '.') {
                last_pnt = i;
            }
        }
        addResearch(new Research(path_name.substring(0, last_pnt), code));
    }

    public void renameReseachWithFile(Research r_rsch, String new_name) {
        System.out.println("Name: "+r_rsch.getName());
        if (researches.contains(r_rsch)) {
            String dir = (String) Configurator.getConf()
                    .getProperty(Configurator.RESEARCH_PATH);
            String file_ext = (String) Configurator.getConf()
                    .getProperty(Configurator.RESEARCH_EXT_FILES);
            warningFileExt(file_ext);

            File fdir = new File(dir);
            if (fdir.exists()) {
                if (fdir.isDirectory()) {
                    File r_file = new File((fdir.getAbsolutePath()
                            + File.separator
                            + ConvFileName.convertName(
                            r_rsch.getName() + file_ext)).replaceAll("\\."+File.separator, ""));
                    File n_file = new File(fdir.getAbsolutePath()
                            + File.separator
                            + ConvFileName.convertName(
                             new_name + file_ext));
                    if (r_file.exists()) {
                        r_file.renameTo(n_file);
                    }
                } else {
                    StendLogger.log(StendLogger.MSG_ERROR, "It is not rename "
                            + "directory: " + dir);
                }
            } else {
                StendLogger.log(StendLogger.MSG_ERROR, "Rename directory not "
                        + "exsist: " + dir);
            }
        }
        r_rsch.setName(new_name);
    }
}
